<?php

class Admin extends MY_Controller {
	
	// essencial data to load the layout
	private $data_layout;
	
	// array with pair 'link'=>'name' menu entries
	private $menuItems;
	
	
	/**
	 * Constructor 
	 */
	function Admin() {
		parent::__construct();
		
		// check if admin is logged in
		if ($this->ion_auth->is_admin()) {
			
			// load model
			$this->load->model('Admin_model'); 
					
			// load language file
			$this->lang->load('admin');
			
			// load nav menu
			$this->_createMenuNav();
			
			// load asset management library ( config file is loaded inside )
			$this->load->library('carabiner');
			
			// load css file for this type of account
			$this->carabiner->css('admin.css');

			// load admin user data
			
		}
		else {
			redirect('Login/index');
		}
	}
	
	
	
	
	
	
	
	/**
	 * Create the navigation menu 
	 */
	private function _createMenuNav() {
		$this->menuItems = 
		array (
			'Admin/index'		=>	$this->lang->line('admin.menu.main'),
			'Admin/list_all'	=>	$this->lang->line('admin.menu.list'),
			'Admin/insert'		=>	$this->lang->line('admin.menu.insert'),
			'Admin/profile'		=>	$this->lang->line('admin.menu.profile'),
			'Admin/users'		=>	$this->lang->line('admin.menu.users')
		);
		
		$this->load->library('fuelmenu');
	} 
	
	
	
	
	
	
	/**
	* Get the menu tags to be sent to the view
	*/
	private function _getMenu() {
	
		// set this link with class="active"
		$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading');
		
		// render the menu
		return $this->fuelmenu->render($this->menuItems,$active,NULL,'basic');
	}
	
	
	
	
	
	
	/**
	 * Entry point
	 */
	public function index() {
		
		// load layout info
		$data = $this->Admin_model->getLayoutInfo();
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		$data['groupLibraries'] = array('jquery','jqueryui');
		
		// load local assets
		
		// render the menu
		$data['menu'] = $this->_getMenu();
		
		// call and send data to view
		$this->load->view('admin/adminview_main',$data);
	}
	
	
	/**
	 * List all users
	 */
	public function list_all() {
		
		// get website layout information
		$data = $this->Admin_model->getLayoutInfo();
		
		// witch group libraries we will need in this view? 
		$data['groupLibraries'] = array('jquery','jqueryui','jtable_1.5.1','validationEngine');
		
		// load local assets
		$this->carabiner->js('jquery.jtable.js','jquery.jtable.min.js');
		$this->carabiner->css('themes/standard/blue/jtable_blue.css');
		$validationEngine = array (
			array('jquery.validationEngine.js'),
			array('jquery.validationEngine-en.js')
		);
		$this->carabiner->js($validationEngine);
		$this->carabiner->css('validationEngine.jquery.css');
		$this->carabiner->js('userList.js');
		
		// render the menu
		$data['menu'] = $this->_getMenu();
		
		// call and send data to view
		$this->load->view('admin/adminview_list',$data);
	}
	
	
	/**
	 * Create a new user
	 */
	public function insert() {
		
		if ($_POST) {	// ... if information is sent
			
			// set array rules
			$rules = array(
				array(
	                     'field'   => 'user',		// name of the form field
	                     'label'   => 'User',		// label used in the information messages
	                     'rules'   => 'required'	// rules ....
				),
				array(
	                     'field'   => 'mail',
	                     'label'   => 'Mail',
	                     'rules'   => 'required|valid_email'
				),
				array(
	                     'field'   => 'first_name',
	                     'label'   => 'First Name',
	                     'rules'   => ''			// we dont need rules here
				),
				array(
	                     'field'   => 'last_name',
	                     'label'   => 'Last Name',
	                     'rules'   => ''
				),
				array(
	                     'field'   => 'pass',
	                     'label'   => 'Password',
	                     'rules'   => 'required|matches[pass_chk]'
				),
				array(
	                     'field'   => 'pass_chk',
	                     'label'   => 'Password confirmation',
	                     'rules'   => 'required'
				)
			);
			
			// set form rules
			$this->form_validation->set_rules($rules);
			
			// create two rules defined by me
			$this->form_validation->set_rules('xxx','"xxx"','callback_userexists_check');
			$this->form_validation->set_rules('yyy','"yyy"','callback_emailexists_check');
			
			// define error delimiters so these can be customized with css styles
			$this->form_validation->set_error_delimiters('<p class="error">','</p>');
						
			// see if the previous rules are ok
			if ($this->form_validation->run()) {
				
				// create user with the following parameters (user, pass, mail, aditional data(first_name,last_name), group)
				$this->ion_auth->register($_POST['user'],$_POST['pass'],$_POST['mail'], array('first_name'=>$_POST['first_name'],'last_name'=>$_POST['last_name']),$_POST['userType']);
			}
			else {	// ... when this point is reached, the user was already notified
			}
		}
		
		// get data layout
		$data = $this->Admin_model->getLayoutInfo();
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		$data['groupLibraries'] = array();
		
		// render the menu
		$data['menu'] = $this->_getMenu();
		
		// call and send data to view
		$this->load->view('admin/adminview_insert',$data);
	}
	
	
	/**
	* Change the current admin user profile
	*/
	public function profile() {
	
		// layout info
		$data = $this->Admin_model->getLayoutInfo();
	
		// witch group libraries we will need in this view? 
		$data['groupLibraries'] = array();
		
		// load local assets
		
		// render the menu
		$data['menu'] = $this->_getMenu();
		
		// treat the POST request
		if ($_POST) {
			// ... if information is sent
				
			// set form input rules
			$this->form_validation->set_rules('old_pass','"old password"',		'required');
			$this->form_validation->set_rules('new_pass','"new password"',		'required|matches[chk_pass]');
			$this->form_validation->set_rules('chk_pass','"Retype password"',	'required');
				
			// define error delimiters so these can be customized with css styles
			$this->form_validation->set_error_delimiters('<p class="error">','</p>');
				
			// see if the previous rules are ok ...
			if ($this->form_validation->run()) {
	
				// change the password of the current admin user
				$identity = $this->session->userdata($this->config->item('identity','ion_auth'));
				$change = $this->ion_auth->change_password($identity,$this->input->post('old_pass'),$this->input->post('new_pass'));
				if ($change) {
					//if the password was successfully changed
					$this->session->set_flashdata('message', $this->ion_auth->messages());
					//$this->logout();
				}
				else {
					//$this->session->set_flashdata('message', $this->ion_auth->errors());
					$this->form_validation->set_message('emailexists_check','email already exists');
				}
				//$bolVar = $this->ion_auth->change_password($this->ion_auth->get_user()->id,$_POST['old_pass'],$_POST['new_pass']);
				//Fb::log($bolVar);
					
			}
			else { // if there is javascript validation ... it should never ever enter here (but only if)
	
			}
		}
		else { 				// ... no data sent ... do nothing
				
		}
	
		// call and send data to the view
		$this->load->view('admin/adminview_profile', $data);
	}
	
	
	public function users() {
	
		// load layout info
		$data = $this->Admin_model->getLayoutInfo();
	
		// witch libraries we need in this view? only those will be loaded in the head view file
		$data['groupLibraries'] = array('jquery');
	
		// render menu
		$data['menu'] = $this->_getMenu();
	
		// call and send data to view
		$this->load->view('admin/adminview_users',$data);
	}
	
	
	
	public function tmpLink() {
		
		// load layout info
		$data = $this->Admin_model->getLayoutInfo();
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		$data['groupLibraries'] = array('jquery');
		
		// load local assets
		
		// render menu
		$data['menu'] = $this->_getMenu();
		
		// call and send data to view
		$this->load->view('admin/adminview_tmp',$data);
	}
	
	
	
	
	/**
	 * CALLBACK FUNCTION to check if the user exists
	 * This is a callback rule function ... so ... it will return
	 * false if the user exists because the rule doesnt pass
	 * @return boolean - FALSE if exists TRUE otherwise
	 */
	public function userexists_check() {	
		$this->form_validation->set_message('userexists_check','this user already exists');
		if ($this->ion_auth->username_check($_POST['user'])) {
			return false;
		}
		else {
			return true;
		}
	}
	
	/**
	* CALLBACK FUNCTION to check if the email exists
	* This is a callback rule function ... so ... it will return
	* false if the user exists because the rule doesnt pass
	* @return boolean - FALSE if exists TRUE otherwise
	*/
	public function emailexists_check() {
		$this->form_validation->set_message('emailexists_check','email already exists');
		if ($this->ion_auth->email_check($_POST['mail'])) {
			return false;
		}
		else {
			return true;
		}
	}
	
	
	/**
	 * jtable send information with GET request to this method
	 * possible paremeters received in GET:
	 *  
	 * if paging=true: 
	 * 		jtStartIndex: 	Start index of records for current page.
	 * 		jtPageSize: 	Count of maximum expected records.
	 * 
	 * @return: TotalRecordCount: Total count of records (not only this page).
	 * 
	 * if sorting=true AND defaultSorting is enabled
	 * 		jtSorting: A string representing the requested sorting ... 
	 * It is built from sorting field name plus sorting direction ... 
	 * For instance, It can be 'Name ASC', 'BirtDate DESC', 'Age ASC'... etc.
	 * 
	 * @return 
	 * 
	 */
	public function listAction() {
		
		// test JSON Objects
		$tmp = ' { "Result":"OK", "Records":[ { "id":			1, "Type":			"hotel", "User":			"h1", "Mail":			"h1@mail.com" }, { "id":			2, "Type":			"hotel", "User":			"h2", "Mail":			"h2@mail.com" }, { "id":			3, "Type":			"school", "User":			"s1", "Mail":			"s1@mail.com" }, { "id":			4, "Type":			"school", "User":			"s2", "Mail":			"s1@mail.com" }, { "id":			5, "Type":			"hotel", "User":			"h3", "Mail":			"h3@mail.com" } ], "TotalRecordCount":5 } ';
		$person_json = ' { "Result":"Ok", "Records":[ { "id":			1, "active":		"1", "Type":			"hotel", "User":			"h1", "Mail":			"h1@mail.com" } ], "TotalRecordCount":1 } ';
		$userinfo = ' { "Result":"OK", "Records":[ { "id":"3", "active":"1", "groupName":"school", "username":"sc1", "email":"sc1@mail.com", "first_name":"sc1", "last_name":"sc1" } ], "TotalRecordCount":1 } '; 

	   	echo  $this->Admin_model->getUsers_JSON();
	}
	
	
	
	/**
	 * When a new user is created in jtable, a POST request is maded
	 * with all fields necessary to update de user ...
	 * ... then the newly created record (an JSON obj) must be returned 
	 * 
	 */
	public function createAction() {
		
		// check if all POST fields are ok ... implement later
		
		if (isset($_POST))
			echo $this->Admin_model->addUser($_POST); 
		//Fb::log($_POST);
		$tmp = '
			{ 
				"Result":"OK",
				"Record":
				[ 
					{ 
						"id":			"5", 
						"active":		"1", 
						"groupname":	"hotel", 
						"username":		"h20", 
						"email":		"h1@mail.com",
						"first_name":	"h20",
						"last_name":	"h20" 
					} 
				]
			}';
		
		//echo $tmp;
		
// 		$json = 
// 		'
// 		{
// 			"Result":"ERROR",
// 			"Message":"nao foi possivel criar"
		
// 		}
// 		';
		
		//echo $json;
		
		
	}
	
	
	/**
	 * Ajax POST(with 'id' and the updated data) is maded from jtable
	 * Update user info ...
	 * @return json object with "Result":"OK" or "Result":"ERROR" with "Message":"info message"
	 * 
	 */
	public function updateAction() {
		$id = $_POST['id'];
		$data = array('first_name'=>$_POST['first_name'],'last_name'=>$_POST['last_name']);
		// get info from this var
		//echo '{ "Result":"OK"}';
		// update the user and show message
// 		if (isset($_POST))
		echo $this->Admin_model->updateUser($id,$data);
	}
	
	
	/**
	* Ajax POST request is maded from jtable with the 'id' of the user to delete
	* @return json object with "Result":"OK" or "Result":"ERROR" with "Message":"info message"
	*
	*/
	public function deleteAction() {

		$msg = '';
		
		if ($this->ion_auth->delete_user($_POST['id'])) {
			$msg = '{"Result":"OK"}';
		}
		else {
			$msg = '{"Result":"ERROR","Message":"error trying to delete user"}';
		}
		
		echo $msg;
	}
	
	
	
	/**
	* Logout the admin user from the system
	*/
	public function logout() {
		$this->ion_auth->logout();
		redirect('Main/index');
	}
	
	
	
	
	
	
	/**
	 * Tmp function
	 */
	public function  tmp() {
		//$this->ion_auth->change_password(4, 'sc2', '00');	
		//$this->firephp->log($_POST);
		
		//$values = '{"field01":"val 1","field2":"val 2"}';
		
		//echo $this->Admin_model->getUsers(null);
		//$this->Admin_model->tmp();
		//$this->firephp->log($this->ion_auth->get_user());
	}
	
	
	
	
	
	
}

